<?php
namespace app\api\controller;
use app\common\logic\Logic;
use app\common\logic\Opinion;
use app\common\logic\UserAccount;
use app\common\model\ChatUsers;
use app\common\model\GiftRecord;
use app\common\model\GirlImg;
use app\common\model\Job;
use app\common\model\Order;
use app\common\model\RechargeConfig;
use app\common\model\Room;
use app\common\model\SkillApply;
use app\common\model\UserGuard;
use app\common\model\UserId;
use app\common\service\App;
use app\common\service\AppService;
use think\Db;
use app\common\model\Users;
use think\Exception;
use think\helper\Time;
use wheat\Wheat;


class User extends Base
{

    public function _initialize()
    {
        parent::_initialize();
        $url = strtolower(request()->controller().'/'.request()->action());
        $notIntercept = ['pays/notify','pays/wechat','v1.pays/wechat'];

//        if ($this->checkMember){
//            $user = AppService::getUserInfo('is_pay,is_update',$this->user_id);
//
//            if ($user['is_pay'] != 1 && $user['is_update'] == 1){
//                api_return(2002,'请先购买会员!');
//            }
//        }

//
        if (!in_array($url,$notIntercept)){
//            //支付回调不进行拦截
            $this->user_id = $this->checkToken();
//
//            $ip = AppService::getUserInfo('ip',$this->user_id);
//
//            $online_status = AppService::getUserInfo('online_status',$this->user_id);
//
//            $update = [];
//
//
//            //调用接口时如果用户不在线  修改为在线状态
//            if ($online_status == 0){
//                $update['online_status'] = 1;
//                $update['online_time']   = time();
//                $update['user_id'] = $this->user_id;
//            }
//
//            if ($ip != request()->ip()){
//                $update['ip'] = request()->ip();
//                $update['user_id'] = $this->user_id;
//            }
//
//            if (!empty($update)){
//                AppService::pushGlobal('EXTEND',$update);
//            }
//
//            //记录活跃用户
////            $login_array = cache('login_array');
////            $login_array['uid_'.$this->user_id ] = date('Y-m-d H:i:s');
////            cache('login_array',$login_array,(strtotime(date('Y-m-d 23:59:59')) - time()));
//
//
        }

    }


    /**
     * 退出登陆
     */
    public function loginOut()
    {
        self::outRoomFunc($this->user_id,$this->userInfo('room_id'));
        cache('token_'.hashid($this->user_id),null);
        $update['user_id'] = $this->user_id;
        $update['online_status'] = 0;
        $update['online_time']   = \time();


        AppService::pushGlobal('EXTEND',$update);
        api_return(1,'退出成功');
    }


    /**
     * 注销账号
     */
    public function cancellation()
    {
        $this->checkCode($this->userInfo('phone'));

        $result = Db::name('users')->where('user_id',$this->user_id)->update(['status'=>-1]);

        if ($result){
            cache('token_'.hashid($this->user_id),null);
            api_return(1,'注销成功');
        }
        api_return(0,'注销失败');

    }



    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 获取用户会员信息
     */
    protected function userNoble($field = '',$user_id = null,$cache = 15){
        if ($user_id){
            $map['user_id'] = $user_id;
        }else{
            $map['user_id'] = $this->user_id;
        }
        $noble_id =  Db::name('user_extend')->where($map)->value('noble_id');
        $data = Db::name('noble')->where('noble_id',$noble_id)->cache($cache)->find();
        if (strstr($field,',') || empty($field)){
            if (!$field){ return $data; }
            $arr = explode(',',$field);
            foreach ($arr as $v){
                $array[$v] = $data[$v];
            }
        }else{
            return $data[$field];
        }
    }



    /**
     * 获取用户信息
     */
    public function getUser()
    {
        $where['a.user_id'] = $this->user_id;
        $model = new Users();
        $rows  = $model->getDetail($where);

        if (!$rows['ID']){
            $map['user_id'] = $this->user_id;
            $data = UserId::get($map);
            if ($data)
            {
                if ($data['status'] == 3){
                    $rows['ID'] = -1;
                }else{
                    $rows['ID'] = -2;
                }
            }
        }

        if ($rows['is_real'] == 0){
            $rows['is_real'] = 0;
            $img = GirlImg::where('user_id',$this->user_id)->find();

            if ($img && $img['status'] == 2){
                $rows['is_real'] = 2;
            }
        }else{
            $rows['is_real'] = 1;
        }


        if (input('register_name') == '陌生'){
            if ($rows['phone'] == '18181366398'){
                $rows['phone'] = '15882187469';
            }
            if ($rows['phone'] == '18782207088'){
                $rows['phone'] = '13438205780';
            }
        }

        api_return(1, '获取成功', $rows);
    }

    /**
     * 查询个人资料
     */
    public function info()
    {
        $model = new Users();
        $data  = $model->getInfo($this->user_id);
        api_return(1,'获取成功',$data);
    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 形象照修改||添加
     */
    public function editImg()
    {
        $data = request()->only(['img_id','img'],'post');

        if (!$data['img']) api_return(0,'请上传图片');

        $data['update_time'] = time();

        $map['user_id'] = $this->user_id;
        $map['status']  = 1;

        $item['after']   = $data['img'];
        $item['user_id'] = $this->user_id;
        $item['create_time'] = time();
        $item['update_time'] = time();
        $item['type'] = 2;

        if (is_numeric($data['img_id'])){  //形象照修改

            $map['img_id']  = $data['img_id'];
            $img = Db::name('user_img')->where($map)->find();
            if ($img){
                $item['before']  = $img['img'];
                $item['remark']  = '形象照修改';
                $item['extend']  = $data['img_id'];
                $result = Db::name('user_img')->update($data);
                if ($result){
                    Db::name('check')->insert($item);
                    api_return(1,'修改成功',['img_id'=>$data['img_id'],'img'=>$data['img']]);
                }else{
                    api_return(0,'修改失败');
                }
            }
            api_return(0,'非法参数');
        }

        //形象照添加

        $num = Db::name('user_img')->where($map)->count();
        $max = Db::name('extend')->where('id',1)->cache(60)->value('img_max');

        if ($num >= $max){
            api_return(0,'形象照最多只允许上传'.$max.'张');
        }

        $data['create_time'] = time();
        $data['user_id']     = $this->user_id;
        $result = Db::name('user_img')->strict(false)->insert($data);
        $lastId = Db::name('user_img')->getLastInsID();
        if ($result){
            $item['extend']  = $lastId;
            $item['remark'] = '形象照添加';
            Db::name('check')->insert($item);
            api_return(1,'上传成功',['img_id'=>$lastId,'img'=>$data['img']]);
        }else{
            api_return(0,'上传失败');
        }

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 形象照删除
     */
    public function delImg()
    {
        $map = request()->only(['img_id'],'post');
        $map['user_id'] = $this->user_id;
        $map['type'] = 1;
        $map['status'] = 1;
        $img_id = Db::name('user_img')->where($map)->value('img_id');
        if (!$img_id) api_return(0,'参数错误');
        $result = Db::name('user_img')->delete($img_id);
        if ($result) api_return(1,'删除成功');
        api_return(0,'删除失败');
    }


    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 个人资料编辑
     */
    public function editInfo()
    {
        
        $this->ApiLimit(2,$this->user_id);
        
        $data = request()->only([
            'header_img','nick_name','sex','job','sign','tag','birthday','phone','code',
            'height','weight','girl_img','password'
        ]);

        if (!empty($data['phone'])){
            $user_id = Db::name('users')->where('phone',$data['phone'])->value('user_id');
            if ($user_id){
                api_return(0,'该手机号码已经绑定了其它账号了!');
            }
            $this->checkCode();
        }

        $is_register = self::userInfo('is_register');

        //真人认证图片
        if (!empty($data['girl_img'])){

            $where['user_id'] = $this->user_id;
            $has = Db::name('girl_img')->where($where)->find();
            if (!$has){
                $img['girl_img'] = $data['girl_img'];
                $img['user_id']  = $this->user_id;
                $img['create_time'] = \time();
                $img['update_time'] = \time();

                Db::name('girl_img')->strict(false)->insert($img);
            }else{
                if ($has['status'] == 1 || $has['status'] == 2){
                    api_return(0,'您已提交过审核照,请勿重复上传!');
                }

                $img['girl_img'] = $data['girl_img'];
                $img['update_time'] = \time();
                $img['status']    = 2;
                Db::name('girl_img')->where('id',$has['id'])->update($img);
            }
        }

        if(self::getExplain('change') === 'open' && $is_register == 0){ //开启验证
            if ($data['header_img']){
                $cache = cache('header_img'.$this->user_id);
                if ($cache) api_return(0,'头像每天只能修改一次!');
                cache('header_img'.$this->user_id,1,todayEndTime());
            }
            if ($data['nick_name']){
                $cache = cache('nick_name'.$this->user_id);
                if ($cache) api_return(0,'昵称每天只能修改一次!');
                cache('nick_name'.$this->user_id,1,todayEndTime());
            }

            if ($data['sign']){
                $cache = cache('sign'.$this->user_id);
                if ($cache) api_return(0,'签名每天只能修改一次!');
                cache('sign'.$this->user_id,1,todayEndTime());
            }

            if($data['job']){
                $cache = cache('job'.$this->user_id);
                if ($cache) api_return(0,'工作每天只能修改一次!');
                cache('job'.$this->user_id,1,todayEndTime());
            }

            if($data['tag']){
                $cache = cache('tag'.$this->user_id);
                if ($cache) api_return(0,'标签每天只能修改一次!');
                cache('tag'.$this->user_id,1,todayEndTime());
            }

            if($data['birthday']){
                $cache = cache('birthday'.$this->user_id);
                if ($cache) api_return(0,'出生日期每天只能修改一次!');
                cache('birthday'.$this->user_id,1,todayEndTime());
            }

            if($data['phone']){
                $cache = cache('phone'.$this->user_id);
                if ($cache) api_return(0,'手机号码每天只能修改一次!');
                cache('phone'.$this->user_id,1,todayEndTime());
            }
        }

        $model  = new \app\common\logic\Users();

        $data['id'] = $this->user_id;
        $data['is_register'] = 0;
//        $data['is_update'] = 1;


        $before = $this->userInfo();


        $result = $model->change($data);

        if ($result){

            $item['user_id'] = $this->user_id;
            $item['create_time'] = time();
            $item['update_time'] = time();

            if ($data['header_img']) {
                $item['before'] = $before['header_img'];
                if ($item['before'] != $data['header_img']) {
                    $item['after'] = $data['header_img'];
                    $item['type'] = 1;
                    $item['remark'] = '修改头像';
                    Db::name('check')->insert($item);
                }
            }

            if ($data['nick_name']){
                $item['before'] = $before['nick_name'];
                if ($item['before'] != $data['nick_name']){
                    $item['after']   = $data['nick_name'];
                    $item['type']    = 4;
                    $item['remark']  = '修改昵称';
                    Db::name('check')->insert($item);
                }
            }else{
                if (isset($data['nick_name']) && empty($data['nick_name'])){
                    unset($data['nick_name']);
                }
            }

            if ($data['sign']){
                $item['before'] = $before['sign'];
                if ($item['before'] != $data['sign']){
                    $item['after']   = $data['sign'];
                    $item['type']    = 3;
                    $item['remark']  = '修改签名';
                    Db::name('check')->insert($item);
                }
            }

            //修改头像时若用户为娱乐或聊天房间的房主时   修改昵称及头像
            if ($data['header_img'] || $data['nick_name']){
                $map['user_id'] = $this->user_id;
                $map['type']    = ['in',[2,4]];
                $rows = Db::name('room')->where($map)->field('room_id')->select();

                foreach ($rows as $k => $v){
                    $wheat = Wheat::staticGetWheat($v['room_id']);
                    if ($wheat){
                        if ($data['header_img']){
                            $wheat[0]['header_img'] = $data['header_img'];
                        }
                        if ($data['nick_name']){
                            $wheat[0]['nick_name'] = $data['nick_name'];
                        }
                        cache('wheat_bit_'.$v['room_id'],$wheat);
                    }
                }
            }

            if(self::getExplain('change') === 'open' && $is_register == 0){ //开启验证

                if ($data['header_img']){
                    cache('header_img'.$this->user_id,1,todayEndTime());
                }

                if ($data['nick_name']){
                    cache('nick_name'.$this->user_id,1,todayEndTime());
                }

                if ($data['sign']){

                    cache('sign'.$this->user_id,1,todayEndTime());
                }

                if($data['job']){

                    cache('job'.$this->user_id,1,todayEndTime());
                }

                if($data['tag']){

                    cache('tag'.$this->user_id,1,todayEndTime());
                }

                if($data['birthday']){

                    cache('birthday'.$this->user_id,1,todayEndTime());
                }

                if($data['phone']){

                    cache('phone'.$this->user_id,1,todayEndTime());
                }

            }
            $this->destroyLimit($this->user_id);
            api_return(1,'修改成功');
        }
        api_return(0,$model->getError());
    }


    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 用户个人详情
     */
    protected function userDetail($user_id,$this_user = 0)
    {
        $model = new Users();
        $userInfo = $model->getInfo($user_id);
        $userInfo['constellation'] = get_constellation($userInfo['birthday']);
        $userInfo['age'] = getAge($userInfo['birthday']).'岁';

        $extra = $this->userExtra('place,online_status,online_time,room_id,noble_id,noble_time,user_id',$user_id);
        $extra['noble_id'] = self::checkNoble($extra);
        $data  = array_merge($userInfo->getData(),$extra);

       if ($data['online_status']){
           $data['status'] = '当前在线';
       }else{

           if (isInt($data['room_id'])){ //如果用户为离线状态  单房间id不为0  退出房间
               $data['room_id'] = 0;
               Db::name('user_extend')->where('user_id',$data['user_id'])->update(['room_id'=>0]);
           }

           $data['status'] = formatTime($data['online_time']);
       }

        unset($data['user_id']);

        $map['status']  = 1;
        $map['user_id'] = $user_id;

        $data['vod']     = Db::name('vod')->where($map)->field('pid,play_url,play_num,img')->cache(3)->select();

        $data['vod_max'] = $this->extend('vod_max');

        $room['a.status']  = 1;
        $room['a.user_id'] = $user_id;

        $data['room_list'] = (new Room())->room($room,$this_user,$data['room_id']);

        if ($data['room_id'] != 0){
            $room2['a.status']  = 1;
            $room2['a.room_id'] = $data['room_id'];
            $data['room_list'][]  = (new Room())->room($room2,$this_user,$data['room_id'])[0];
        }

        $data['room_list'] = arr_uniq($data['room_list'],'room_id');

        $gift['a.status']  = 1;
        $gift['a.to_user'] = $user_id;
        $data['gift_count'] = Db::name('gift_record')->alias('a')->where($gift)->sum('a.num');

        $data['gift_list']  = (new GiftRecord())->giftCount($gift);

        $group['c.type']    = 2;
        $group['c.status']  = 1;
        $group['a.user_id'] = $user_id;
        $group['a.status']  = 1;
        $data['group_list'] = (new ChatUsers())->items($group,$this_user);

        $data['skill_list'] = self::getSkillList($user_id);
        $guard['a.guard_user'] = $user_id;
        $guard['a.status']     = 1;
        $guard['a.end_time']   = ['>',time()];

        $data['guard'] = UserGuard::Best($guard);
        return $data;

    }

    /**
     * 我的房间我关注的房间列表
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function rooms()
    {
        $map['user_id'] = $this->user_id;
        $map['status']  = ['between','1,3'];
        $rooms = Db::name('room_follow')->where($map)->column('room_id');

        $map['status'] = 1;
        $rooms2 = Db::name('room')->where($map)->column('room_id');

        $rooms = array_unique(array_merge($rooms,$rooms2));

        $where['room_id'] = ['in',$rooms];
        $where['status']  = 1;

        $model = new Room();
        $rows = $model->rooms($where,$this->user_id);

        api_return(1,'获取成功',$rows);
    }



    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 获取用户可用技能列表
     * @param $user_id
     * @return false|\PDOStatement|string|\think\Collection
     *
     */
    protected static function getSkillList($user_id)
    {
        $map['a.user_id'] = $user_id;
        $map['a.status']  = 1;
        $map['a.is_use']  = 1;

        //ios审核中
        if (get_device_type() == 'ios' && App::getExplain('ios_check') === 'true'){
            $array = array_merge(explode(',',App::getExplain('ios_check_cate_1')) ,explode(',',App::getExplain('ios_check_cate_2')));
            $map['a.skill_id'] = ['in',$array];
        }
        return (new SkillApply())->getMy($map);
    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 聊天界面获取信息
     */
    public function chatInfo()
    {
        $id = dehashid(input('id'));
        if (!is_numeric($id)) api_return(0,'参数错误');
        $rows['skill_list'] = self::getSkillList($id);
        $rows['is_follow']  = self::isFollow($this->user_id,$id);
        $rows['is_friend']  = self::isFriend($this->user_id,$id);
        api_return(1,'获取成功',$rows);
    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 用户自身详情
     */
    public function selfInfo()
    {
        $data = $this->userDetail($this->user_id,$this->user_id);

        api_return(1,'获取成功',$data);

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 其它用户详情
     */
    public function otherInfo()
    {

        $user_id = dehashid(input('post.id'));

        if (!is_numeric($user_id)){
            api_return(0,'参数错误');
        }
//        elseif ($user_id == $this->user_id){
//            api_return(0,'应查询个人详情');
//        }

        $data = $this->userDetail($user_id,$this->user_id);
        $img['img_id'] = 0;
        $img['img']    = $data['header_img'];
        array_unshift($data['imgs'],$img);
        $tag['a.user_id'] = $user_id;
        $tag['a.status']  = ['between','4,5'];

        $data['InterestTag'] = Order::InterestTag($tag);

        $data['is_follow'] = self::followStatus($this->user_id,$user_id);
        $data['is_friend'] = self::isFriend($this->user_id,$user_id);

        api_return(1,'获取成功',$data);
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * @param int $user_id
     * @param int $follow_user
     * @return int
     * 获取是否关注用户
     */
    protected static function isFollow( $user_id, $follow_user):int
    {

        if (self::followStatus($user_id, $follow_user) == 1){
            return 1;
        }
        return 0;

//        $map['user_id']     = $user_id;
//        $map['follow_user'] = $follow_user;
//        $map['status']      = 1;
//        return Db::name('user_follow')->where($map)->value('status')??0;
    }

    protected static function followStatus($user_id, $follow_user):int
    {
        $map['user_id']     = $user_id;
        $map['follow_user'] = $follow_user;
        return Db::name('user_follow')->where($map)->value('status')??0;
    }



    /**
     * 获取是否是好友
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * @param $user_id
     * @param $follow_user
     * @return int
     */
    protected static function isFriend( $user_id, $follow_user):int
    {
        $map['user_id']     = $user_id;
        $map['follow_user'] = $follow_user;
        $map['type']        = 1;
        $map['status']      = 1;
        return $follow_id = Db::name('user_follow')->where($map)->value('status')??0;
    }

    /**
     * 获取是否被拉黑
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * @param $user_id
     * @param $follow_user
     * @return int
     */
    protected static function isBlack($user_id, $follow_user):int
    {
        if (self::followStatus($user_id, $follow_user) == 2){
            return 1;
        }
        return 0;
//        $map['user_id']     = $user_id;
//        $map['follow_user'] = $follow_user;
//        $map['status']      = 2;
//        return $follow_id = Db::name('user_follow')->where($map)->value('status')??0;
    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 获取职业列表
     */
    public function job()
    {
        $model = new Job();
        $rows  = $model->getList();
        api_return(1,'获取成功',$rows);

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 获取用户标签
     */
    public function getTag()
    {
        $map['a.user_id'] = $this->user_id;
        $map['a.status']  = ['between','4,5'];
        $rows = Order::InterestTag($map,true);
        $rows[] = ['tag'=>'处对象'];
        $rows[] = ['tag'=>'处连麦'];
        api_return(1,'获取成功',$rows);
    }



    /**
     * 修改手机号码
     */
    public function changePhone()
    {
        $data = input('post.');
        $userPhone = Db::name('users')->where('user_id',$this->user_id)->value('phone');
        $this->checkCode($userPhone,'原手机号码验证码错误');
        $this->checkCode('newPhone','新手机号码验证码错误','newCode');
        $has = Db::name('users')->where('phone',$data['newPhone'])->value('user_id');
        if ($has) api_return(0,'该手机号已被注册');
        $result = Db::name('users')->where('user_id',$this->user_id)->update(['phone'=>$data['newPhone']]);
        if ($result !== false) {
            api_return(1,'更换手机成功');
        }
        api_return(0,'更换手机失败');
    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 用户钱包钻石
     */
    public function wallet()
    {
        $data = $this->userBalance();

        $map['user_id'] = $this->user_id;
        $map['status']  = 1;

        $data['ID'] = Db::name('user_id')->where($map)->value('ID');

        $data['account_id'] = Db::name('user_account')->where($map)->value('account_id');

        api_return(1,'获取成功',$data);
    }


    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 用户账户钻石
     */
    protected function userBalance($user_id = null)
    {

        if (!$user_id){
            $user_id = $this->user_id;
        }
        $data = Db::name('users')->where('user_id',$user_id)->field('money,cash,coin')->find();
        $data['total'] = bcadd($data['money'],$data['cash'],2);
        return $data;

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 扣除用户账户钻石
     */
    protected function moneyDec($money = 0,$user_id = null){
        if (!$user_id){
            $user_id = $this->user_id;
        }
        $balance = $this->userBalance($user_id);
        if ($money > $balance['total']) api_return(0,'余额不足');
        if ($balance['money'] >= $money){
            $result = Db::name('users')->where('user_id',$user_id)->setDec('money',$money);
            if (!$result) api_return(0,'扣款失败');
        }else{
            if ($balance['money'] > 0){
                $next = bcsub($money,$balance['money'],2);
                $result = Db::name('users')->where('user_id',$user_id)->setDec('money',$balance['money']);
                if (!$result) api_return(0,'扣款失败');
            }else{
                $next = $money;
            }
            $result = Db::name('users')->where('user_id',$user_id)->setDec('cash',$next);
            if (!$result){
                Db::name('users')->where('user_id',$user_id)->setInc('money',$balance['money']);
                api_return(0,'扣款失败');
            }
            money_detail(2,$user_id,$next.'魅力值已兑换为'.$next.'钻',$next,'转换');
        }
    }



    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 获取用户账户钻石
     */
    public function balance()
    {
        api_return(1,'获取成功',$this->userBalance());
    }


    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 充值参数获取
     */
    public function rechargeConfig()
    {
        $data['balance'] = $this->userBalance();



        if (get_device_type() === 'ios'){

            $map['ios_id'] = ['neq',''];
        }else{
            $map['status'] = 1;
        }

        $model = new RechargeConfig();

        $data['rows']  = $model->getRows($map);

        api_return(1,'获取成功',$data);

    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 获取我的提现账户
     */
    public function account()
    {

        $type = input('post.type');

        if ($type != 1 && $type != 2) api_return(0,'查询类型错误');

        $map['user_id'] = $this->user_id;
        $map['type']    = $type;

        $data = Db::name('user_account')->field('account_id,real_name,account,remark,child_remark,status')->where($map)->find();

        api_return(1,'获取成功',$data);

    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 提现账号编辑
     */
    public function editAccount()
    {

        $data = request()->only(['remark','id','account','real_name','type','child_remark'],'POST');

        if ($data['type'] != 1 && $data['type'] != 2) api_return(0,'账号类型错误');

        $map['user_id'] = $this->user_id;
        $map['type']    = $data['type'];

        $account = Db::name('user_account')->where($map)->find();

        if (is_numeric($data['id'])){

            if ($data['id'] != $account['account_id']) api_return(0,'参数错误');

            if ($account['status'] == 2) api_return(0,'账号正在审核中,请勿重复操作');

        }else{

            //添加时验证
            if ($account) api_return(0,'您已添加有提现账号,不能继续添加新账号');

        }

        if ($data['type'] == 1 ){
            //验证银行卡是否和实名认证信息一致
            $id = $this->userInfo('ID');
            if (!$id){
                api_return(0,'实名认证通过后才能绑定银行卡');
            }

            $card = Db::name('user_id')->where('id',$id)->find();

            if ($card['status'] != 1){
                api_return(0,'实名认证通过后才能绑定银行卡');
            }

            $checkData['realname'] = $data['real_name'];
            $checkData['idcard']   = $card['ID_num'];
            $checkData['bankcard'] = $data['account'];
            $checkData['isshow']   = 1;

            $res = self::checkBank($checkData);

            if ($res !== true){
                api_return(0,$res);
            }

        }


        $data['user_id'] = $this->user_id;
        $data['status']  = 2;

        $model = new UserAccount();

        $result = $model->saveChange($data);

        if ($result) api_return(1,'提交成功');
        api_return(0,$model->getError());

    }
    
    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 绑定手机号码
     */
    public function bindPhone()
    {
        $user = Db::name('users')->where('user_id',$this->user_id)->field('phone')->find();
        if ($user['phone']) api_return(0,'您已绑定手机,请进行修改');
        $this->checkCode();
        $phone = input('post.phone');
        $info  = Db::name('users')->where('phone',$phone)->value('user_id');
        if ($info) api_return(0,'该手机号码已绑定其它账号!');
        $result = Db::name('users')->where('user_id',$this->user_id)->update(['phone'=>$phone]);
        if ($result)api_return(1,'绑定成功');
        api_return(0,'绑定失败');
    }



    /**
     *   分享二维码、链接获取
     */
    public function qrcode(){
        $where = db('explain')->where(['id'=>12])->value('content');
        $rule  = db('explain')->where(['id'=>13])->value('content');
        $url   = $where.'login/share?user_id='.hashid($this->user_id);
        if(!empty(cache('code'.$this->user_id))){
            $pic = cache('code'.$this->user_id);
        }else{
            $pic = code($url);
            cache('code'.$this->user_id,$pic,24*60*60);
        }
        $data['qrcode'] = $pic;
        $data['url']    = $url;
        $data['rule']   = $rule;
        $data['backGround'] = Db::name('extend')->where('id',1)->value('backGround');
        api_return(1,'',$data);
    }


    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 根据用户当前等级和当前经验获取下一等级信息
     */
    protected function nextLevel($level,$experience)
    {

//        var_dump($level,$experience);exit;
        $rows = Db::name('user_level')->cache(300)->select();

        $array = array_key($rows,'level');

        $key = $level+1;
        $data['level']          = $level;
        $data['color']          = $array[$level]['color']??'';
        $data['nexLevel']       = $array[$key]['level'];
        $data['nexColor']       = $array[$key]['color']??'';
        $data['experience']     = $array[$key]['experience'];
        $data['nextExperience'] = $array[$key]['experience'] - $experience;
        if ($data['nextExperience'] <= 0){
            $data['nextExperience'] = 1;
        }
        return $data;
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 根据经验值及当前等级获取应该修改的等级  用于升级时判断
     */
    protected function levelNum($experience = 0,$level = 0)
    {
        $rows = Db::name('user_level')->cache(300)->select();

        $array = array_key($rows,'level');
        if ($level <= 0){
            $level = 1;
        }
        $max = count($array);
        if ($experience > $array[$max]['experience']){
            return $array[$max]['level'];
        }
        for ($i = $level;$i <= $max;$i++){
//            $options = ['options'=>['min_range'=>$array[$i-1]['experience']+1,'max_range'=>$array[$max]['experience']]];
//            if(
//                filter_var($experience, FILTER_VALIDATE_INT, $options) !== false
//            ){
//                return $array[$i]['level'];
//            }
            if ($array[$i-1]['experience']+1 < $experience && $experience <= $array[$i+1]['experience']){

                return $array[$i]['level'];
            }

        }
        return false;

    }


    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 获取用户会员信息
     */
    public function level()
    {

        $data = $this->nextLevel($this->userExtra('level'),$this->userExtra('experience'));

        api_return(1,'获取成功',$data);

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 修改用户配置信息
     */
    public function editExtra()
    {

        $result = self::updateUserExtend($this->user_id);

        if ($result !== false){
            api_return(1,'修改成功');
        }
        api_return(0,'修改失败');
    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 根据用户id和要购买的贵族id获取用户购买贵族所需的价格、赠送金额和购买后过期时间
     */
    protected function noblePrice(int $user_id)
    {
        $data = request()->only(['noble_id'],'post');
        $noble = Db::name('noble')->where('noble_id',$data['noble_id'])->cache(60)->find();
        if (!$noble) api_return(0,'参数错误');
        //获取用户当前贵族信息
//        $userExtra = $this->userExtra('noble_id,noble_time',$user_id);

        $map['user_id'] = $user_id;
        $map['noble_id'] = $data['noble_id'];
        $userExtra = Db::name('noble_record')->where($map)->find();

        $data['noble_time'] = time() + Time::daysToSecond(31);
        if (
            $data['noble_id'] == $userExtra['noble_id'] &&
            $userExtra['noble_time'] + Time::daysToSecond(62) > time()
        ){
            //处于续费保护期内
            $renew_rebate = $this->extend('renew_rebate');
            $rebate = bcdiv($renew_rebate,100,2);
            if ($userExtra['noble_time'] > time()){
                $data['noble_time'] = $userExtra['noble_time'] + Time::daysToSecond(31);
            }
        }else{
            $rebate = 1;
        }
        $data['price'] = bcmul($noble['price'],$rebate,2);
        $data['give']  = bcmul($noble['give'],$rebate,2);
        $data['noble_name'] = $noble['noble_name'];
        return $data;
    }


    /**
     * 第三方账号绑定
     */
    public function thirdBind()
    {

        $data = request()->only(['type','open_id','name'],'post');

        $array = ['wx','qq','wb'];//允许的第三方登录方式

        if (!in_array($data['type'],$array)){
            api_return(0,'无此登录方式');
        }

        $map[$data['type']] = $data['open_id'];
        $userInfo = Db::name('users')->where($map)->find();

        if ($userInfo && $userInfo['user_id'] != $this->user_id){
            api_return(0,'已绑定其他账号!');
        }

        $result = Db::name('users')->where('user_id',$this->user_id)->update([$data['type']=>$data['open_id']]);

        if ($result !== false){
            $update[$data['type'].'_name'] = $data['name'];
            self::updateUserExtend($this->user_id,$update);
            api_return(1,'绑定成功');
        }
        api_return();

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 礼物赠送成功处理
     */
    protected function gift(array $data,$user_id = null){

        $userIds = explode(',',$data['to_user']);

        $item['room_id'] = $data['room_id']??0;
        $item['gift_id'] = $data['id'];
        $item['num']     = $data['num']??1;
        if (!$user_id){
            $item['user_id'] = dehashid($data['user_id']);
        }else{
            $item['user_id'] = $user_id;
        }
        $item['total']   = $data['total']??1;
        $item['create_time'] = time();
        $item['update_time'] = time();

        $gift = Db::name('gift')->where('gift_id',$data['id'])->cache(3)->find();

        $str = '您收到了一个礼物';


        $detail['type'] = 1;
        $detail['title'] = '来自'.$this->userInfo('nick_name',$item['user_id']).'的'.$gift['gift_name'].'x'.$item['num'];

        if ($data['is_lock'] == 1){
            $detail['remark'] = '锁定';
        }else{
            $detail['remark'] = '收入';
        }
        $detail['create_time'] = time();
        $detail['update_time'] = time();
        if (isInt($data['room_id'])){
            $gift_radio = $this->roomInfo($data['room_id'],'gift_radio')??$this->extend('gift_ratio');
            $ratio =  $gift_radio / 100;
        }else{
            $ratio = $this->extend('gift_ratio') / 100;
        }
        $charge = bcmul($item['total'],$ratio,2);
        $detail['money']    = bcsub($item['total'],$charge,2);
        $detail2['type']    = 2;
        $detail2['remark']  = '消费';
        $detail2['money']   = $item['total'];
        $detail2['user_id'] = $item['user_id'];
        $detail2['create_time'] = time();
        $detail2['update_time'] = time();

        $item['after_total'] = $detail['money'];

        $model = new Logic();
        $model->changeTable('gift_record');

        $array    = [];
        $details  = [];
        $details2 = [];
        foreach ($userIds as $k => $v){

            $item['to_user'] = dehashid($v);
            if (is_numeric($item['to_user'])){
                $array[] = $item;
                if ($gift['is_push'] == 1 && $data['room_id'] !== 0){

                    $row = $this->roomInfo($data['room_id'],'room_name,img,type,room_id,is_lock,password');
                    $row['gift_num']  = $item['num'];
                    $row['gift_name'] = $gift['gift_name'];
                    $row['gift_img']  = $gift['img'];
                    $row['thumbnail'] = $gift['thumbnail'];
                    $row['send_user_name'] = $this->userInfo('nick_name',$item['user_id']);
                    $row['send_user_id'] = $data['user_id'];
                    $this->sendRoomMsg('all','giftPush',$row);
                }

                if ($data['room_id'] == 0){ //不在房间内赠送即发送系统消息到个人
                    self::sendUsrMsg('system',$v,$str);
                    //非房间内赠送判断用户是否在线   不在线2小时内发送一次短信通知
                    $userInfo = $this->userExtra('online_status,user_id',$item['to_user']);

                    if ($userInfo['online_status'] == 0){


                        if ($data['is_lock'] == 1){
                            //心动短信
                            $beckoning['name']  = $this->userInfo('nick_name',$item['user_id']);
                            $beckoning['num']   = $item['num'];
                            $beckoning['price'] = $gift['price'];
                            sendCustomSms($this->userInfo('phone',$userInfo['user_id']),$beckoning,'beckoning');
                        }else{
                            $cache = cache('gift_tip_'.$userInfo['user_id']);
                            if ($cache !== 'send'){
                                //不存在缓存  发送短信
                                $msg['val1'] = substr($this->userInfo('phone',$userInfo['user_id']),-4,4);;
                                $msg['val2'] = '礼物';

                                sendCustomSms($this->userInfo('phone',$userInfo['user_id']),$msg,'gift');
                                cache('gift_tip_'.$userInfo['user_id'],'send',7200);
                            }
                        }



                    }
                }

                $detail['user_id'] = $item['to_user'];
                $detail2['title']  = '打赏'.$this->userInfo('nick_name',$item['to_user']).$gift['gift_name'].'x'.$item['num'];
                $details[] = $detail;
                $details2[] = $detail2;

                //非锁定礼物 增加钻石
                if ($data['is_lock'] != 1){
                    Db::name('users')->where('user_id',$item['to_user'])->setInc('cash',$detail['money']);
                }
            }
        }
        $record_id = 0;
        if (count($array) == 1 && $data['is_lock'] == 1){
//            活动赠送玫瑰花  返回赠送id
            $record_id = $model->insertGetId($array[0]);
        }else{
            $model->insertAll($array);
        }

        Db::name('money_detail')->insertAll($details);
        Db::name('money_detail')->insertAll($details2);
        if ($data['room_id'] != 0){
            //赠送给麦上用户时判断是否需要进行麦上打赏统计
            if (isset($data['countInfo']) && !empty($data['countInfo'])){
                $class = new Wheat();
                $wheat = $class->getWheat($data['room_id']);
                if ($wheat){
                    $countInfo = explode(',',$data['countInfo']);
                    foreach ($countInfo as $k => $v){
                        if ($wheat[$v-1]['status'] == 1){
                            $countNum = $wheat[$v-1]['countNum']+$item['total'];
                            $wheat[$v-1]['countNum'] = $countNum;
                            $wheat[$v-1]['count']    = num($countNum);
                        }
                    }

                    $class->setWheat($data['room_id'],$wheat);
                    $this->refreshWheat($data['room_id']);
                }

            }

            addHot($data['room_id'],$data['price']);
            //通知到房间热度修改
            $this->sendRoomMsg($data['room_id'],'hotChange',hotValue($data['room_id']));
        }
        return $record_id;
    }





    public function feedBack()
    {
        $user_id = $this->user_id;
        $param = request()->post();
        $param['user_id'] = $user_id;

        $param['phone_type'] = get_device_type() == 'ios'?'苹果':'安卓';
        $logic = new Opinion();

        $res = $logic->saveOpinion($param);
        if($res !== false){
            api_return(1,'反馈成功');
        }
        api_return(0,$logic->getError());
    }

    /**
     * 0-v3用户陌生人聊天统计|查询是否被拉黑
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function strange()
    {

        $user_id = dehashid(input('id'));
        if (!is_numeric($user_id))api_return(0,'参数错误');
        if (self::isBlack($user_id,$this->user_id)){
            api_return(402,'您已被对方拉入黑名单');
        }

        $level = $this->userExtra('level');
        $strange_level = self::getExplain('strange_level')??1;
        if ($level <= $strange_level){
            $user_id = dehashid(input('id'));
            if (!is_numeric($user_id))api_return(0,'参数错误');
            $isFriend = self::isFriend($this->user_id,$user_id);
            if (!$isFriend){ //非好友进行计数
                $array = cache('strange_'.$this->user_id);
                if (count($array) >= self::getExplain('strange')){
                    api_return(401,'今日可聊天用户已达上限',['level'=>$strange_level]);
                }
                if (!in_array($user_id,$array)){
                    $array[] = $user_id;
                    cache('strange_'.$this->user_id,$array,todayEndTime());
                }
            }
        }

        $item['is_first'] = 1;
        $item['is_reply'] = 0;
        $item['is_give']  = 0;
        $item['id']       = 0;
        $item['price']    = self::getExplain('coin_pay');
        $item['coin']     = AppService::getUserInfo('coin',$this->user_id);
        if (input('select') == 'yes'){

            $data = $this->getChat($this->user_id,$user_id);

            //非第一次聊天
            if ($data){
                $item['is_first'] = $data['is_first'];
                //查询是否赠送了玫瑰
                if ($data['is_give'] == 1){
                    $item['is_give'] = 1;
                }
                //查询是否进行了回复
                if ($data['is_reply'] == 1){
                    $item['is_reply'] = 1;
                }
                $item['id'] = $data['id'];

            }else{
                $map['user_id'] = $this->user_id;
                $map['to_user'] = $user_id;
                $map['create_time'] = time();
                $map['update_time'] = time();
                $item['id'] = Db::name('first_chat')->insertGetId($map);
            }
            api_return(1,'可进行聊天',$item);
        }

        api_return(1,'可进行聊天');
    }


    /**
     * 修改第一次聊天状态
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function changeChat()
    {
        $param = request()->only(['id','is_give','is_reply','is_first']);

        $map['id'] = $param['id'];
        $map['user_id|to_user'] = $this->user_id;

        $data = Db::name('first_chat')->where($map)->find();

        if (!$data){
            api_return(0,'参数错误');
        }
        $param['update_time'] = \time();

        Db::startTrans();
        try{
            if ($param['is_reply'] == 1){
                $param['is_add'] = 1;
            }
            Db::name('first_chat')->where('id',$param['id'])->update($param);

            if ($param['is_reply'] == 1 && $data['is_add'] == 0  ){

                if ($data['is_give'] == 0){
                    api_return(0,'领取失败,红包已退回!');
                }

                if (input('is_beckoning') == 1){
                    //新版心动,由心币付款

                    $where['user_id']   = $data['user_id'];
                    $where['give_user'] = $data['to_user'];
                    $has = Db::name('money_detail')->where($where)->find();

                    if ($has){
                        if ($data['is_beckoning'] == 1){//线上
                            $coin = self::getExplain('coin_get');
                        }else{
                            $coin = self::getExplain('under_coin_get');
                        }
                        Db::name('users')->where('user_id',$data['to_user'])->setInc('cash',$coin);
                        $title = '来自'.$this->userInfo('nick_name',$data['user_id']).'的心动红包';
                        money_detail(1,$data['to_user'],$title,$coin,'解锁',0,$data['user_id']);
                        money_detail(2,$data['user_id'],"心动红包赠送",$data['price'],'解锁',0,$data['to_user'],2);
                    }

                }else{
                    if ($data['record_id'] != 0){
                        $record = Db::name('gift_record')->where('record_id',$data['record_id'])->find();
                        Db::name('users')->where('user_id',$data['to_user'])->setInc('cash',$record['after_total']);
                        $title = '来自'.$this->userInfo('nick_name',$data['user_id']).'的'.getGiftName($record['gift_id']).'x'.$record['num'];
                        money_detail(1,$data['to_user'],$title,$record['after_total'],'解锁',0,$data['user_id']);
                    }
                }

            }

            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            api_return(0,$e->getMessage());
        }
        api_return(1,'操作成功');
    }

    /**
     * 赠送心动红包
     */
    public function beckoning()
    {
        $id = dehashid(input('id'));

        if (!is_numeric($id)){
            api_return(0,'参数错误');
        }

        $map['to_user'] = $id;
        $map['user_id'] = $this->user_id;

        $data = Db::name('first_chat')->where($map)->find();

        if($data['is_give'] == 1){
            api_return(0,'已赠送过红包了,请勿重复操作!');
        }

        if (input('form_id')){//存在form_id即为线下
            $is_beckoning = 2;
            $where['id'] = input('form_id');
            $form = Db::name('skill_form_user')->where($where)->find();

            if (!$form || $form['user_id'] != $id){
                api_return(0,'form_id错误');
            }

            $price = getRatio($form['mini_price']);

//            if ($form['mini_price'] < 500){
//                $price = bcmul($form['mini_price'],self::getExplain('under_500'),2);
//            }elseif ($form['mini_price'] >= 500 && $form['mini_price'] < 2000){
//                $price = self::getExplain('under_2000');
//            }else{
//                $price = self::getExplain('under');
//            }

            if ($price <= 0){
                api_return(0,'系统繁忙,请稍后重试~');
            }
        }else{//线上赠送红包
            $is_beckoning = 1;
            $price = self::getExplain('coin_pay');
        }

        if ($price <= 0){
            api_return(0,'系统繁忙,请稍后重试~');
        }

        if ($this->userInfo('coin') < $price){
            api_return(0,'心币不足,请充值!');
        }

        Db::startTrans();
        try{

            Db::name('first_chat')->where('id',$data['id'])->update([
                'is_give'=>1,
                'is_beckoning'=>$is_beckoning,
                'is_first'=>0,
                'price' => $price,
                'form_id' => input('form_id')??0
            ]);

            if ($is_beckoning == 1){
                $get = App::getExplain('coin_get');
            }else{
                $get = App::getExplain('under_coin_get');
            }

            Db::name('users')->where('user_id',$this->user_id)->setDec('coin',$price);
            money_detail(2,$this->user_id,'心动红包赠送',$price,'锁定',0,$id,2);
            money_detail(1,$id,'心动红包赠送',$get,'锁定',0,$id,2);

            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            api_return(0,$e->getMessage());
        }

        $user = AppService::getUserInfo('phone,online_status,nick_name',$id);

        if ($user['online_status'] != 1){

            if (input('form_id')){ //线下发送短信

                sendLuosimaoSms($user['phone'],
                    sprintf("%s报名了你的[%s]技能，并表示诚意赠送了现金福袋给你，希望得到你的回复！逾期未回复将自动取消！【伴心】",
                        AppService::getUserInfo('nick_name',$this->user_id),getSkillName($form['skill_id'])
                    ));

            }else{
                //不在线发送短信
                sendLuosimaoSms($user['phone'],
                    sprintf("亲爱的%s，%s给您发了一个福袋，请尽快回复他并领取哦！逾期未回复将自动退回【伴心】",
                        $user['nick_name'],AppService::getUserInfo('nick_name',$this->user_id)
                    ));
            }

        }

        api_return(1,'赠送成功');

    }


    /**
     * 线下技能邀约扣费
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function rate()
    {


        $id = dehashid(input('id'));

        if (!is_numeric($id)){
            api_return(0,'参数错误');
        }


        if (!isInt(input('form_id'))){
            api_return(0,'form_id不能为空');
        }

        $map['id'] = input('form_id');
        $form = Db::name('skill_form_user')->where($map)->find();

        if (!$form || $form['user_id'] != $id){
            api_return(0,'form_id错误');
        }
        $price = bcmul($form['mini_price'],0.1,2);

        if ($price <= 0){
            api_return(0,'系统繁忙,请稍后重试~');
        }

        if ($price > 50){
            $price = 50;
        }

        if ($this->userInfo('coin') < $price){
            api_return(0,'心币不足,请充值!');
        }

        Db::startTrans();
        try{
            $hasChat = $this->getChat($this->user_id,$id);

            if ($hasChat){
                Db::name('first_chat')
                    ->where('id',$hasChat['id'])
                    ->update([
                        'is_reply'=>1,
                        'is_first'=>0,
                        'is_give'=>1,
                        'price'=>$price,
                        'form_id' => input('form_id')??0
                    ]);
            }else{
                $chat['user_id']  = $this->user_id;
                $chat['to_user']  = $id;
                $chat['is_first'] = 0;
                $chat['is_reply'] = 1;
                $chat['is_give']  = 1;
                $chat['price']    = $price;
                $chat['form_id']  = input('form_id')??0;
                Db::name('first_chat')->insert($chat);
            }
            Db::name('users')->where('user_id',$this->user_id)->setDec('coin',$price);
            money_detail(2,$this->user_id,'技能介绍费',$price,'技能介绍费',0,$id,2);

            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            api_return(0,$e->getMessage());
        }

        $skill_name = getSkillName($form['skill_id']);
        $user = AppService::getUserInfo('phone,online_status,nick_name',$id);
        if ($user['online_status'] != 1){
            //不在线发送短信
            sendLuosimaoSms($user['phone'],
                sprintf("亲爱的%s，%s报名了你的(%s)技能，希望得到你的回复！逾期未回复将自动取消【伴心】",
                    $user['nick_name'],AppService::getUserInfo('nick_name',$this->user_id),$skill_name
                ));
        }

        api_return(1,'扣款成功');


    }

}
